package com.yjt.sousou.detail;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.yjt.sousou.Api;
import com.yjt.sousou.R;
import com.yjt.sousou.base.BaseActivity;
import com.yjt.sousou.create.entity.Finish;
import com.yjt.sousou.detail.entity.EventUser;
import com.yjt.sousou.detail.entity.FilterBean;
import com.yjt.sousou.detail.entity.Group;
import com.yjt.sousou.detail.entity.UserEntity;
import com.yjt.sousou.http.DialogCallback;
import com.yjt.sousou.user.LoginTag;
import com.yjt.sousou.utils.HDPreference;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：83734
 * 时间：2018/11/25
 * 描述：派工
 */
public class DispatchingActivity extends BaseActivity {
    /**
     * 派工
     */
    public static final int FROM_DISPATCH = 10;
    /**
     * 从填写维修过程页面过来选人
     */
    public static final int FROM_PROCESS = 11;
    public static final String KEY_FROM = "key_from";
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.rv_people_list)
    RecyclerView mRvPeopleList;
    DispatchingAdapter mAdapter;
    @BindView(R.id.tv_state)
    TextView mTvState;
    @BindView(R.id.tv_group)
    TextView mTvGroup;
    @BindView(R.id.ll_filter)
    LinearLayout mLlFilter;
    @BindView(R.id.tv_submit)
    TextView mTvSubmit;
    private DispatchPop mStatePop;
    private DispatchPop mGroupPop;
    private String mStateId = "";
    private String mGroupId = "";
    private String orderId;
    private int mFrom = FROM_DISPATCH;

    private List<FilterBean> mStateData = new ArrayList<>();
    private List<FilterBean> mGroupData = new ArrayList<>();

    ArrayList<UserEntity.DataBean> mUserList = new ArrayList<>();

    @Override
    protected Object setContentLayout() {
        return R.layout.activity_dispatching;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        mFrom = getIntent().getIntExtra(KEY_FROM, FROM_DISPATCH);
        mTvTitle.setText(mFrom == FROM_DISPATCH ? R.string.order_detail_dispatching : R.string.order_select_person);
        mTvSubmit.setText(mFrom == FROM_DISPATCH ?"确认派工":"确认选择");
        initRecycleView();
        orderId = getIntent().getStringExtra("orderId");
        mUserId = HDPreference.getUserId(LoginTag.USER_ID.name());
        mStateData.add(new FilterBean("", "全部", false));
        mStateData.add(new FilterBean("1", "在岗", false));
        mStateData.add(new FilterBean("2", "不在岗", false));
        getGroup();
    }


    private void initData() {
        OkGo.<UserEntity>get(Api.get().getRepairs())
                .tag(this)
                .params("state", mStateId)
                .params("fenzu", mGroupId)
                .execute(new DialogCallback<UserEntity>(UserEntity.class, this) {
                    @Override
                    public void onSuccess(Response<UserEntity> response) {
                        if (response.isSuccessful()) {
                            UserEntity body = response.body();
                            if (body.getReturncode().equals("0")) {
                                mUserList.clear();
                                mUserList.addAll(body.getData());
                                mAdapter.notifyDataSetChanged();
                            } else {
                                showToast("没有数据");
                            }
                        }
                    }
                });
    }

    private void getGroup() {
        if (mFrom == FROM_DISPATCH) {
            initData();
            OkGo.<Group>get(Api.get().getGroup())
                    .tag(this)
                    .execute(new DialogCallback<Group>(Group.class, this) {
                        @Override
                        public void onSuccess(Response<Group> response) {
                            Group group = response.body();
                            mGroupData.add(new FilterBean("", "全部", false));
                            for (Group.DataBean dataBean : group.getData()) {
                                mGroupData.add(new FilterBean(dataBean.getId(), dataBean.getFenzu(), false));
                            }
                        }
                    });
        } else {
            OkGo.<Group>get(Api.get().getProcessGroup()).tag(this)
                    .params("user_id",mUserId)
                    .execute(new DialogCallback<Group>(Group.class, this) {
                        @Override
                        public void onSuccess(Response<Group> response) {
                            Group group = response.body();
                            if(group!=null&&group.getData()!=null){
                                if(group.getData().size()>0){
                                    mGroupId = group.getData().get(0).getId();
                                }
                                initData();
                                for (Group.DataBean dataBean : group.getData()) {
                                    mGroupData.add(new FilterBean(dataBean.getId(), dataBean.getFenzu(), false));
                                }
                            }
                        }
                    });
        }
    }

    private void initRecycleView() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRvPeopleList.setLayoutManager(manager);
        mAdapter = new DispatchingAdapter(R.layout.item_dispathing_list, mUserList);
        mRvPeopleList.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mUserList.get(position).setSelected(!mUserList.get(position).isSelected());
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick({R.id.tv_state, R.id.rl_group, R.id.tv_submit})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_state:
                if (mStatePop == null) {
                    mStatePop = new DispatchPop(this, mStateData, 0, new DispatchPop.GetIdsListener() {
                        @Override
                        public void ids(String id) {
                            LogUtils.i("ids:", id);
                            mStateId = id;
                            initData();
                        }

                        @Override
                        public void dismiss() {
                            setDismissState(mStateId, mTvState);
                        }
                    });
                }
                showOrDismiss(mStatePop, mGroupPop);
                setTextColor(mStatePop, mTvState);
                break;
            case R.id.rl_group:
                if (mGroupPop == null) {
                    mGroupPop = new DispatchPop(this, mGroupData, 0, new DispatchPop.GetIdsListener() {
                        @Override
                        public void ids(String id) {
                            LogUtils.i("ids:", id);
                            mGroupId = id;
                            initData();
                        }

                        @Override
                        public void dismiss() {
                            setDismissState(mGroupId, mTvGroup);
                        }
                    });
                }
                showOrDismiss(mGroupPop, mStatePop);
                setTextColor(mGroupPop, mTvGroup);
                break;
            case R.id.tv_submit:
                if (mFrom == FROM_DISPATCH) {
                    //确认派工
                    submit();
                } else {
                    //确认人员选择
                    EventUser eventUser = new EventUser(
                            mAdapter.getUserIds(),mAdapter.getSelectUsers());
                    EventBus.getDefault().post(eventUser);
                    finish();
                }
                break;
        }
    }

    /**
     * 确认派工
     */
    private void submit() {
        String userIds = mAdapter.getUserIds();
        OkGo.<Finish>post(Api.get().getOrderDispatch())
                .tag(this)
                .params("ids", orderId)
                .params("user_ids", userIds)
                .params("opt_uid", mUserId)
                .execute(new DialogCallback<Finish>(Finish.class, this) {
                    @Override
                    public void onSuccess(Response<Finish> response) {
                        Finish finish = response.body();
                        if (finish.getReturncode().equals("0")) {
                            showToast("指派成功");
                            finish();
                        } else {
                            showToast("指派失败：" + finish.getReturnmsg());
                        }
                    }
                });
    }

    private void showOrDismiss(DispatchPop popWindow0, DispatchPop popWindow1) {
        if (popWindow0.isShowing()) popWindow0.dismiss();
        else popWindow0.show(mLlFilter, 0, 10);
        if (popWindow1 != null) popWindow1.dismiss();
    }

    private void setTextColor(DispatchPop pop, TextView tv) {
        if (pop.isShowing()) {
            tv.setTextColor(ContextCompat.getColor(this, R.color.text_color));
            tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.arrow_up, 0);
        } else {
            tv.setTextColor(ContextCompat.getColor(this, R.color.black));
        }
    }

    private void setDismissState(String id, TextView tv) {
        tv.setTextColor(ContextCompat.getColor(this, R.color.black));
        tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.arrow_down, 0);
    }
}
